#!/usr/bin/env python

# common interface to ippool

from django.utils.timezone import now

from ippool.models import Host

def get_host():	
	"""Returns a dict ipaddress, port if available, None otherwise."""

	try:
		hosts = Host.objects.filter(is_alive = True).order_by('-used_on')
		if len(hosts) > 0:
			host = hosts[0]
			host.used_on = now()
			host.save()
			return {'ipaddress': host.ipaddress, 'port': host.port}
	except Exception, e:
		# TODO: log error to ippool.log
		print 'Failed to get_host reason: %s' % e
	
	return None

def set_is_alive(ipaddress, port, is_alive):
	try:
		host = Host.objects.get(ipaddress = ipaddress, port=port)
		host.is_alive = is_alive
		host.save()
	except Exception, e:
		# TODO: log error to ippool.log
		print 'Failed to set is_alive flag reason: %s' % e
		
def is_alive(ipaddress, port):
	try:
		host = Host.objects.get(ipaddress = ipaddress, port=port)
		return host.is_alive
	except Exception, e:
		# TODO: log error to ippool.log
		return False


if __name__ == '__main__':
	host = get_host()
	if host:
		print '%s:%s' % (host['ipaddress'], host['port'])
